 #-*- coding: utf-8 -*-

import logging 
 
import psycopg2
import tokenize
import optparse

 
'''
  <CONFIGURATION SECTION>
'''
PROJECT_CODE=5
 
"""

Files to import can be foudn cvbrun:Mercury@192.168.2.30

Usage: python import_camera_positions.py -c "host='192.168.2.63' dbname='cyclo' user='cyclo' password='cyclo'" -f 000_CheckLogFound_10.txt

Usage:  for i in $( ls 000*.txt ); do python import_camera_positions.py -c "host='192.168.2.63' dbname='cyclo' user='cyclo' password='cyclo'" -f $i ; done


"""
 
 

'''
  </CONFIGURATION SECTION>
'''


logger = logging.getLogger("database")


'''
Should return theSQL to execute
'''
def lineHandlerCSVJBWaterwegen( inSplittedLineArray ):
    if len( inSplittedLineArray ) != 12:
      logger.error( "Invalid line [%s]" % ( inSplittedLineArray ) )
      return None
    
    theFullPath =    inSplittedLineArray[0].replace( './','7/Waterwegen/')
    theXCoordinate = inSplittedLineArray[3]
    theYCoordinate = inSplittedLineArray[4]
    theZZCoordinate = inSplittedLineArray[5]
    theHeading = inSplittedLineArray[6]
    theDeviation = inSplittedLineArray[7]
    theVelocity = inSplittedLineArray[8]
    theDateTimeOfRecording = inSplittedLineArray[9]
    theJulianDayOfRecording = inSplittedLineArray[10]
    theNISCode = inSplittedLineArray[11]
    
    theInsertStatement = "insert into sch_camera_pos.camerapos values ( nextval('sch_camera_pos.seq_camerapos_id'::regclass), '%s', ST_GeomFromEWKT('SRID=31370;POINT(%.12f %.12f %.12f)'),%.12f,%.12f,%.12f,to_timestamp( '%s','YYYY MM DD HH24 MI SS'),%.12f,%d,%d );" \
      % ( theFullPath, float(theXCoordinate), float(theYCoordinate), float(theZZCoordinate), float(theHeading), \
	float(theDeviation), float(theVelocity), theDateTimeOfRecording, float(theJulianDayOfRecording), int( theNISCode ), PROJECT_CODE)    
  
    return theInsertStatement
  


  

def processFile( inFile, inConnectionString, inLineHandler ):
  print inFile
  
  theDbConnection = None
  try:
       theDbConnection = psycopg2.connect(inConnectionString)
       print "Connected to database"
  except KeyboardInterrupt, e:
       raise
  except Exception, e:
       logger.warning( e )
       if theDbConnection != None:
           theDbConnection.rollback()
       print( "I am unable to connect to the database" )
  theCur = theDbConnection.cursor()
  
  
  for line in open(inFile):
    theSplittedLine = line.split(',')
    
    theSQLToExecute = inLineHandler( theSplittedLine )
    
    if ( theSQLToExecute == None ):
      logger.info( "Nothing to execute ")
    else:
      logger.info( "Gonna execute [%s]" % (theSQLToExecute ) )
      theCur.execute( theSQLToExecute )  
    
    
  theDbConnection.commit()  
  theDbConnection.close()
						
    
    

def main():    
    logger.info("About to fill up database")
    
    parser = optparse.OptionParser()
    parser.add_option("-f", "--inputfile", 	dest="inputfile", action="store")
    
    parser.add_option("-c", "--connectionString", 	dest="connectionString", action="store", help="\"dbname='cyclo' schema='sch_session' user='cyclo' host='localhost' password='cyclo'\"")
    
    (options, args) = parser.parse_args()

    if options.inputfile == None:
      print "Provide inputfile please"
      return
    if options.connectionString == None:
      print "Provide connection String please"
      return
    
    processFile( options.inputfile, options.connectionString, lineHandlerCSVJBWaterwegen )



  
if __name__ == "__main__":

  logging.basicConfig(level=logging.INFO)

  main()
  
  
  